package com.black.cat.jvm.classfile;

/**
 * @Author blackcat
 * @create 2021/8/12 8:22
 * @version: 1.0
 * @description:二进制转换处理工具类
 *
 *
 */
public class ByteUtil {

    public static int byteToInt(byte[] codes) {
        String s1 = byteToHexString(codes);
        return Integer.valueOf(s1, 16);
    }

    public static String byteToHexString(byte[] codes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : codes) {
            int value = b & 0xFF;
            String strHex = Integer.toHexString(value);
            if (strHex.length() < 2) {
                strHex = "0" + strHex;
            }
            sb.append(strHex);
        }
        return sb.toString();
    }

    public static String intToHex(int n) {
        if (n < 0) {
            n += 256;
        }

        //StringBuffer s = new StringBuffer();
        StringBuilder sb = new StringBuilder(8);
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            sb = sb.append(b[n % 16]);
            n = n / 16;
        }

        a = sb.reverse().toString();

        if (a.length() == 0) {
            a = "00";
        } else if (a.length() == 1) {
            a = "0" + a;
        }
        return a;
    }

    /**
     * 传入一个long数据，返回一个int数组
     * 高位在前，低位在后
     *
     * @param tmpLong long数据
     * @return int数组
     */
    public static int[] long2IntArr(long tmpLong) {
        int pre, suffix;
//        pre = (int) ((tmpLong >> 16) & 0xffff);       //取高字节
//        suffix = (int) (tmpLong & 0xffff);          //取低字节
        pre = (int) ((tmpLong >> 32) & 0xffffffffL);       //取高字节
        suffix = (int) (tmpLong);          //取低字节
        return new int[]{pre, suffix};
    }

    /**
     * 传入2个int数据，返回一个long数值
     *
     * @param pre    高位
     * @param suffix 低位
     * @return long数据
     */
    public static long int2Long(Integer pre, Integer suffix) {
        long m2 = 0;
        if (Integer.toBinaryString(pre).length() >= 32) {
            m2 = ((pre.longValue()) << 32) | suffix;
        } else {
            String s = Integer.toBinaryString(pre) + getZero(32 - Integer.toBinaryString(suffix).length())
                    + Integer.toBinaryString(suffix);
            m2 = Long.parseLong(s, 2);
        }

        return m2;
    }

    public static String getZero(int length) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            stringBuilder.append("0");
        }
        return stringBuilder.toString();
    }

}
